package com.loadmore.common.activity

import android.graphics.Bitmap
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.zxing.Result
import com.google.zxing.client.result.ParsedResult
import com.loadmore.common.R
import com.loadmore.common.base.BaseActivity
import com.loadmore.common.model.MessageEvent
import com.loadmore.common.router.RouterPath
import com.mylhyl.zxing.scanner.OnScannerCompletionListener
import kotlinx.android.synthetic.main.activity_qrcode.*
import org.greenrobot.eventbus.EventBus

/**
 * 二维码扫描
 * @author sunleilei
 * @date 2018.7.12
 */

@Route(path = RouterPath.QRCode)
class QRCodeActivity : BaseActivity(), OnScannerCompletionListener {
    var web = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        web = intent.getBooleanExtra("web",false)
        setContentView(R.layout.activity_qrcode)
        scanner_view.setOnScannerCompletionListener(this)
    }

    override fun onResume() {
        super.onResume()
        scanner_view.onResume()
    }

    override fun onPause() {
        super.onPause()
        scanner_view.onPause()
    }


    override fun onScannerCompletion(rawResult: Result?, parsedResult: ParsedResult?, barcode: Bitmap?) {
        var result = parsedResult.toString()
        if (web) {
            EventBus.getDefault().post(MessageEvent("","",result))
        }else{
            if (result.startsWith("http") || result.startsWith("https")) {
                var bundle = Bundle()
                bundle.putString("url",result)
                ARouter.getInstance().build(RouterPath.Web).with(bundle ).navigation()
            }else{
                ARouter.getInstance().build(RouterPath.QRCodeResult).withString("result",result).navigation()
            }
        }
        finish()

    }

    override fun onDestroy() {
        super.onDestroy()
    }
}
